package hy.servlet.cmd;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CmdProductor
 */

public class CmdProductor extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String KEY = "hy";
	private static final String ERROR = "error";
    private static final String NOCMD = "nocmd";
    public static final String ATTR_NAME = "cmd";
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CmdProductor() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String message = null;
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		String rkey = request.getParameter("key");
		if(rkey != null && rkey.equalsIgnoreCase(KEY)){
			ServletContext context = request.getSession().getServletContext();
			if(context == null){
				writer.write(ERROR); 
				return;
			}
			String cmd = (String) context.getAttribute(ATTR_NAME);
			if(cmd != null && check(cmd)){
				writer.write(cmd);
				
				context.removeAttribute("cmd");
			}
			else{
				writer.write(NOCMD);
			}
		}
		else{
			writer.write(ERROR);
		}
	}
	
	//此方法对发送过来的cmd命令进行解析和验证，若存在不合法命令，不会发给计算机执行
	private boolean check(String cmd){
		return true;
	}
}
